<template>
  <!-- 销售顾问绩效对比报告 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      height="auto"
      v-loading="loading"
      :mergeCellMethod="objectSpanMethod"
      :dataSource="dataSource"
      :isPagination="false"
      :isSelectColumn="false"
      :isColumnFilter="false"
      selectionType="single"
      :onColumnsChange="columns => this.columns = columns"
    ></FilterTable>
  </div>
</template>

<script>
import { getOrgTeam, getUserByOrgId } from '@/api/report/retail/clueFunnelAnalysis';
import { queryCounselorPerformanceContrast, getPerformanceReportDLRList } from '@/api/report/retail/PerformanceReport';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { integration, integrations, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import moment from 'moment';
export default {
  name: 'PerformanceReport',
  mixins: [dictionary, authority],
  components: {
    Chart1
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {
        startDate:moment().format("YYYY-MM-DD"),
        endDate:moment().format("YYYY-MM-DD")
      },
      quarterTime: [],
      visible: false,
      dialogTitle: '',
      handleType: '',
      formData: {},
      conf: { add: '新增', edit: '编辑', show: '显示' },
      loading: false,
      dataSource: [],
      columns: this.createTableColumns(),
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '日期维度',
          fieldName: 'dateType',
          placeholder: '请选择',
          initialValue: 'day',
          itemList: [
            { value: 'day', text: '日' },
            { value: 'week', text: '周' },
            { value: 'month', text: '月' },
            { value: 'quarter', text: '季' },
            { value: 'year', text: '年' },
            { value: 'date', text: '期间' }
          ],
          change: val => {
            this.changeTemplateType(val);
          }
        },
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD"),
          change: (val, fieldName) => {
            // console.log(val,fieldName)
            this.quarterTime = val;
          }
        },
        {
          type: 'SELECT',
          label: '销售小组',
          fieldName: 'orgIds',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            // console.log(val,fieldName)
            this.getUserByOrgId(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '销售顾问',
          fieldName: 'consultants',
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '销售小组',
          width: 100,
          dataIndex: 'orgName'
        },
        {
          title: '销售顾问',
          width: 100,
          dataIndex: 'consultantName'
        },
        {
          title: '过程转化',
          align: 'center',
          children: [
            {
              title: '线索',
              align: 'center',
              children: [
                {
                  title: '总线索',
                  width: 70,
                  dataIndex: 'totalClue'
                },
                {
                  title: '新增线索',
                  width: 70,
                  dataIndex: 'insertClue'
                },
                {
                  title: '有效线索',
                  width: 70,
                  dataIndex: 'effectiveClue'
                },
                {
                  title: '线索有效率',
                  width: 85,
                  dataIndex: 'effectClueRate'
                },
                {
                  title: '展厅客流量',
                  width: 85,
                  dataIndex: 'hallPassengerFlow'
                }
              ]
            },
            {
              title: '到店',
              align: 'center',
              children: [
                {
                  title: '线索邀约到店量',
                  width: 85,
                  dataIndex: 'inviteToStore'
                },
                {
                  title: '线索邀约到店率',
                  width: 85,
                  dataIndex: 'inviteToStoreRate'
                },
                {
                  title: '展厅客流留档量',
                  width: 85,
                  dataIndex: 'customerFiling'
                },
                {
                  title: '展厅客流留档率',
                  width: 85,
                  dataIndex: 'customerFilingRate'
                }
              ]
            },
            {
              title: '试乘试驾',
              align: 'center',
              children: [
                {
                  title: '试乘试驾量',
                  width: 85,
                  dataIndex: 'testDrive'
                },
                {
                  title: '试乘试驾率',
                  width: 85,
                  dataIndex: 'testDriveRate'
                }
              ]
            },
            {
              title: '订单',
              align: 'center',
              children: [
                {
                  title: '订单量',
                  width: 70,
                  dataIndex: 'orderCount'
                },
                {
                  title: '退订单',
                  width: 70,
                  dataIndex: 'cancelOrderCount'
                },
                {
                  title: '订单率',
                  width: 70,
                  dataIndex: 'orderCountRate'
                },
                {
                  title: '结存订单',
                  width: 70,
                  dataIndex: 'balanceCount'
                }
              ]
            },
            {
              title: '成交',
              align: 'center',
              children: [
                {
                  title: '成交量',
                  width: 70,
                  dataIndex: 'completeCount'
                },
                {
                  title: '成交率',
                  width: 70,
                  dataIndex: 'completeCountRate'
                },
                {
                  title: '订单成交转化率',
                  width: 85,
                  dataIndex: 'orderConversionRate'
                }
              ]
            },
            {
              title: '战败',
              align: 'center',
              children: [
                {
                  title: '战败量',
                  width: 70,
                  dataIndex: 'defeatNum'
                },
                {
                  title: '战败率',
                  width: 70,
                  dataIndex: 'defeatRate'
                }
              ]
            }
          ]
        },
        {
          title: 'KPI指标',
          align: 'center',
          children: [
            {
              title: '线索及首触',
              align: 'center',
              children: [
                {
                  title: '首触任务量',
                  width: 85,
                  dataIndex: 'firstTouchTask'
                },
                {
                  title: '及时首触量',
                  width: 85,
                  dataIndex: 'timelyFirstTouch'
                },
                {
                  title: '及时首触率',
                  width: 85,
                  dataIndex: 'timelyFirstTouchRate'
                }
              ]
            },
            {
              title: '线索有效判定',
              align: 'center',
              children: [
                {
                  title: '线索判定任务量',
                  width: 85,
                  dataIndex: 'clueDetermineTask'
                },
                {
                  title: '及时判定量',
                  width: 85,
                  dataIndex: 'timelyDetermine'
                },
                {
                  title: '及时判定率',
                  width: 85,
                  dataIndex: 'timelyDetermineRate'
                }
              ]
            },
            {
              title: '跟进',
              align: 'center',
              children: [
                {
                  title: '跟进任务量',
                  width: 85,
                  dataIndex: 'followUpTask'
                },
                {
                  title: '及时跟进量',
                  width: 85,
                  dataIndex: 'timelyFollowUp'
                },
                {
                  title: '及时跟进率',
                  width: 85,
                  dataIndex: 'timelyFollowUpRate'
                }
              ]
            }
          ]
        }
      ];
    },
    // 合并行或列的计算方法
    // row:当前行 column:当前列 rowIndex:当前行号 columnIndex:当前列号
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.orgName = '全部';
          return [1, 2];
        } else {
          // 与上一行不相等
          if (row.orgId !== (this.dataSource[rowIndex - 1] || {}).orgId) {
            // 与上一行不相等,与下一行相等
            if (row.orgId === (this.dataSource[rowIndex + 1] || {}).orgId) {
              return {
                rowspan: this.dataSource.filter(x => row.orgId === x.orgId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },

    async getReportDLRList() {
      this.loading = true;

      ObjectAssign([queryCounselorPerformanceContrast, getPerformanceReportDLRList], 'consultant', this.fetchParams, dataSource => {
        console.log(dataSource);
        this.loading = false;
        dataSource = sortRule(dataSource, 'orgId');
        if (dataSource.length > 0) {
          let all1 = computedAll(this.columns[2].children, dataSource);
          let all2 = computedAll(this.columns[3].children, dataSource);
          let all = {...all1,...all2};
          all['orgId'] = 'all';
          all['consultant'] = 'all';
          all['orgName'] = '全部';
          all['consultantName'] = '全部';
          dataSource.unshift(all);
          dataSource.forEach(x => {
            x['effectClueRate'] = GetPercent(x.effectiveClue, x.insertClue);
            x['inviteToStoreRate'] = GetPercent(x.inviteToStore,x.inviteNum)// 暂无邀约量
            x['customerFilingRate'] = GetPercent(x.customerFiling, x.hallPassengerFlow);
            x['testDriveRate'] = GetPercent(x.testDrive, x.keepFileQuantity)// 暂无留档量
            x['orderCountRate'] = GetPercent(x.orderCount, x.keepFileQuantity)// 暂无留档量
            x['completeCountRate'] = GetPercent(x.completeCount, x.keepFileQuantity)// 暂无留档量
            x['orderConversionRate'] = GetPercent(x.completeCount, x.orderCount);
            x['defeatRate'] = GetPercent(x.defeatNum, x.setStorage)// 暂无集客量
            x['timelyFirstTouchRate'] = GetPercent(x.timelyFirstTouch, x.firstTouchTask);
            x['timelyDetermineRate'] = GetPercent(x.timelyDetermine, x.clueDetermineTask);
            x['timelyFollowUpRate'] = GetPercent(x.timelyFollowUp, x.followUpTask);
          });
        }
        this.dataSource = dataSource;
      });
    },
    async getOrgTeam() {
      const res = await getOrgTeam();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'orgIds').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getUserByOrgId(val) {
      const res = await getUserByOrgId({ orgId: val });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = '';
      }
    },
    changeHandle(val) {
      if (val.datetime) {
        switch (val.dateType) {
          case 'day':
            val.startDate = val.datetime;
            val.endDate = val.datetime;
            break;
          case 'week':
            var weekOfday = moment(val.datetime, 'YYYY-MM-DD').format('E'); //计算指定日期是这周第几天
            var last_monday = moment(val.datetime).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(val.datetime).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday;
            val.endDate = last_sunday;
            break;
          case 'month':
            var start_monthday = moment(val.datetime)
              .startOf('month')
              .format('YYYY-MM-DD'); //月初日期
            var last_monthday = moment(val.datetime)
              .endOf('month')
              .format('YYYY-MM-DD'); //月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday;
            val.endDate = last_monthday;
            break;
          case 'quarter':
            val.startDate = this.quarterTime[0].split(' ')[0];
            val.endDate = this.quarterTime[1].split(' ')[0];
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime)
              .startOf('year')
              .format('YYYY-MM-DD'); //年初日期
            var last_yearday = moment(val.datetime)
              .endOf('year')
              .format('YYYY-MM-DD'); //年末日期
            // console.log(start_yearday,last_yearday)
            val.startDate = start_yearday;
            val.endDate = last_yearday;
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            break;
        }
      }
      if (val.consultants.length > 0) {
        val.consultant = getTextByJs(val.consultants);
      }
      if (!val.orgIds) {
        val.orgIds = undefined
      }
      this.fetchParams = Object.assign({}, val);
      this.getReportDLRList();
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 修改日期组件
    changeTemplateType(val) {
      switch (val) {
        case 'day':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'week':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'week';
          this.topFilterList.find(item => item.fieldName==='datetime').firstDayOfWeek = 1;
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'month';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'quarter';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'year';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    }
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getOrgTeam();
    // this.getUserByOrgId()
    this.getReportDLRList();
  }
};
</script>

<style lang="less" scoped>
</style>
